import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import * as THREE from 'three';
// import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';
const loader = new GLTFLoader();
const model = new THREE.Group();
let resolveModelLoaded: (value: THREE.Group) => void;
export const modelLoaded = new Promise<THREE.Group>(resolve => {
  resolveModelLoaded = resolve;
});
const texture = new THREE.TextureLoader().load("/jpg/光标.png");
const spriteMaterial = new THREE.SpriteMaterial({ map: texture });

async function loadModel() {
  try {
    const gltf = await loader.loadAsync("/models/Buletooth_close.gltf");
    model.add(gltf.scene);
    gltf.scene.scale.set(10, 10, 10);
    gltf.scene.position.set(0, -10, 0);
    model.castShadow = true;
    model.receiveShadow = true;
    resolveModelLoaded(model);

  } catch (error) {
    console.error('模型加载失败:', error);
  }
}

document.addEventListener('DOMContentLoaded', () => {
  // model.add(sprite);
  // sprite.scale.set(50, 50,50);
  // sprite.position.set(0,150, 0);
  loadModel();
  modelLoaded.then(() => {
    model.traverse((child) => {
      if (child.name === "电池" || child.name === "Box004") {
        // 创建新的 Sprite 实例
        const sprite = new THREE.Sprite(spriteMaterial);
        child.add(sprite);
  
        sprite.position.copy(child.parent!.position);
        sprite.position.y -= 2.5;
        sprite.scale.set(2, 2, 2);
  
        let scale = 2;
        let direction = 1;
        const minScale = 1;
        const maxScale = 2;
  
        function animateSprite() {
          scale += 0.03 * direction;
          if (scale >= maxScale || scale <= minScale) {
            direction *= -1;
          }
          sprite.scale.set(scale, scale, scale);
          requestAnimationFrame(animateSprite);
        }
  
        animateSprite(); // 启动动画
      }
    });
  });
});

export { model };